<template>
    <div class="user-list-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>用户列表</span>
          </div>
        </template>
        
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="用户名/昵称">
            <el-input v-model="searchForm.username" placeholder="请输入用户名/昵称" clearable />
          </el-form-item>
          
          <el-form-item label="手机号码">
            <el-input v-model="searchForm.phone" placeholder="请输入手机号码" clearable />
          </el-form-item>
          
          <el-form-item label="邮箱">
            <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
          </el-form-item>
          
          <el-form-item label="注册时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 用户表格 -->
        <el-table
          :data="userList"
          border
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="id" label="用户ID" width="80" />
          
          <el-table-column label="头像" width="80">
            <template #default="scope">
              <el-avatar :size="40" :src="getAvatarUrl(scope.row.avatar)">
                {{ scope.row.username.charAt(0).toUpperCase() }}
              </el-avatar>
            </template>
          </el-table-column>
          
          <el-table-column prop="username" label="用户名" width="120" />
          
          <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
          
          <el-table-column prop="phone" label="手机号码" width="130" />
          
          <el-table-column prop="registerTime" label="注册时间" width="180" />
          
          <el-table-column prop="lastLoginTime" label="最后登录" width="180" />
          
          <el-table-column prop="orderCount" label="订单数" width="100" sortable />
          
          <el-table-column fixed="right" label="操作" width="150">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="viewDetail(scope.row)">详情</el-button>
              <el-button link type="primary" size="small" @click="viewOrders(scope.row)">订单</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { getUserList } from '../../api/user'
  
  const router = useRouter()
  const loading = ref(false)
  
  // 搜索表单
  const searchForm = reactive({
    username: '',
    phone: '',
    email: '',
    dateRange: []
  })
  
  // 分页信息
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })
  
  // 用户列表数据
  const userList = ref([])
  
  // 获取用户列表
  const fetchUserList = async () => {
    loading.value = true
    
    try {
      const params = {
        page: pagination.currentPage,
        limit: pagination.pageSize,
        username: searchForm.username,
        phone: searchForm.phone,
        email: searchForm.email,
        startDate: searchForm.dateRange?.[0],
        endDate: searchForm.dateRange?.[1]
      }
      
      const res = await getUserList(params)
      userList.value = res.items
      pagination.total = res.total
    } catch (error) {
      ElMessage.error('获取用户列表失败: ' + error.message)
    } finally {
      loading.value = false
    }
  }
  
  // 搜索
  const handleSearch = () => {
    pagination.currentPage = 1
    fetchUserList()
  }
  
  // 重置搜索
  const resetSearch = () => {
    Object.keys(searchForm).forEach(key => {
      if (key === 'dateRange') {
        searchForm[key] = []
      } else {
        searchForm[key] = ''
      }
    })
    handleSearch()
  }
  
  // 查看用户详情
  const viewDetail = (row) => {
    router.push(`/users/${row.id}`)
  }
  
  // 查看用户订单
  const viewOrders = (row) => {
    router.push({
      path: '/orders',
      query: { userId: row.id }
    })
  }
  
  // 分页大小变化
  const handleSizeChange = (size) => {
    pagination.pageSize = size
    fetchUserList()
  }
  
  // 页码变化
  const handleCurrentChange = (page) => {
    pagination.currentPage = page
    fetchUserList()
  }
  
  // 添加处理头像URL的函数
  const getAvatarUrl = (avatar) => {
    if (!avatar) return '';
    
    // 检查是否已经是完整的URL
    if (avatar.startsWith('http')) return avatar;
    
    // 服务器基础URL
    const serverBaseUrl = 'http://localhost:5000';
    
    // 确保路径正确
    const path = avatar.startsWith('/') ? avatar : `/${avatar}`;
    
    // 如果是相对路径，添加uploads前缀
    if (!path.startsWith('/uploads') && !path.startsWith('/api')) {
      return `${serverBaseUrl}/uploads${path}`;
    }
    
    return `${serverBaseUrl}${path}`;
  }
  
  onMounted(() => {
    fetchUserList()
  })
  </script>
  
  <style scoped>
  .user-list-container {
    padding: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  </style>